package com.hkh.emp.service;

import com.hkh.emp.core.constant.Constant;
import com.hkh.emp.entity.SysUser;
import com.hkh.emp.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 用户操作,实现Spring Security UserDetailService
 *
 * @author wangxian 2021/5/1
 */
@Service
@Slf4j
public class UserServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("Login Username is:{}", username);
        SysUser sysUser = sysUserMapper.selectByUserName(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        return sysUser;
    }

    public SysUser signUp(SysUser user) {
        user.setStatus(1);
        user.setPassword(passwordEncoder.encode(Constant.SIGN_UP_USER_DEFAULT_PASSWORD));
        user.setCreateTime(LocalDateTime.now());
        sysUserMapper.insert(user);
        return user;
    }
}
